from django.contrib import auth
import models
import conf
from django.db.models import ObjectDoesNotExist

def addLocation(user, lon, lat, speed, time):
	location = models.Location(user = user, updated = time, latitude = lat, longitude = lon, speed = speed)
	deletePrevious(user.username, conf.maxCountPerUser)
	location.save()

def userLocations(userName, topCount=None):
	res = models.Location.objects.filter(user__username = userName).order_by("-updated")
	if topCount == None: return res
	return res[:topCount]

def deletePrevious(userName, count):
	reduntant = userLocations(userName)[count-1:]
	for item in reduntant:
		item.delete()

def deleteLocations(user, ids):
	resCount = 0
	for id in ids:
		try:
			loc = models.Location.objects.get(id=id, user=user)
			loc.delete()
			resCount += 1
		except ObjectDoesNotExist:
			pass
	return resCount

